package com.cloudptt.wp.ui.address.map;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.osmdroid.api.IMapController;
import org.osmdroid.tileprovider.IRegisterReceiver;
import org.osmdroid.tileprovider.modules.ArchiveFileFactory;
import org.osmdroid.tileprovider.modules.IArchiveFile;
import org.osmdroid.tileprovider.modules.OfflineTileProvider;
import org.osmdroid.tileprovider.tilesource.FileBasedTileSource;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.SimpleRegisterReceiver;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Polyline;

import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.models.lbs.LocationData;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.wp.R;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.address.map.data.Point;
import com.cloudptt.wp.ui.address.map.ui.MarkerRoundMenu;
import com.cloudptt.wp.ui.address.map.ui.MarkerTools;
import com.cloudptt.wp.ui.address.map.ui.RoundMenuView;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.MapPointInfo;
import com.mcptt.db.model.UserInfo;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

public class MapFragment extends Fragment implements OnClickListener{
	
	private static final String TAG = "MapFragment";

	private static final int NORMAL_MAP = 1;
	private static final int SATALITE_MAP = 2;
	private static final int THREED_MAP = 3; 
	private static final Double ZOOM_LEVEL_MAX = (double)21;
	private static final Double ZOOM_LEVEL_MIN = (double)1;
	
	private static final int[] ZOOM = {50,100,200,
										500,1000,2000,
										5000,10000,20000,
										25000,50000,100000,200000,
										500000,1000000,2000000};
	
	/* add army marker */
	public PopupWindow popupWindow;
	public GeoPoint mArmyMarkPoint;
	public ImageView myMonitor_me, myMonitor_friend, myMonitor_enemy;
	public TextView mLongitude_Mark, mLatitude_Mark, mLocation_Distance;
	public List<Marker> mArmyMarkers = new ArrayList<Marker>();
	public ArrayList<Marker> sendedMarker = new ArrayList<Marker>();
	
	private MapView mMapView;
	IMapController mController;
	private GeoPoint myLocationPoint;
	private GeoPoint defaultPoint;

	private CompassView mCompassView;
	public ImageButton mBtnCenterMap;
	public LinearLayout mZoomButtons;
	public ImageView mZoomIn;
	public ImageView mZoomOut;
	public ListView mContactLv;
	private TextView mCurrentGroupTv;
	
	private RelativeLayout mMapCallLayout;
	private ImageButton mMapCallVideoButton;
	private ImageButton mMapCallVoiceButton;
	private View CallView;
	
	public Map<String, Polyline> mTrackMap = new HashMap<String, Polyline>();

	private BoundingBox sCentralParkBoundingBox;
	//private BoundingBoxE6 mAutoBoundingBoxE6;

	// draw circle button
	RoundMenuView roundMenuView;
	public HashMap<Marker, View> roundMenuMap = new HashMap<Marker, View>();
	int markResource = 0;
	//public HashMap<RoundMenuView.RoundMenu, Marker> roundMarkerMap = new HashMap<RoundMenuView.RoundMenu, Marker>();
	public ArrayList<Marker> mMarkerReceiveList = new ArrayList<Marker>();
	private List<MapPointInfo> mUserLocationList = new ArrayList<MapPointInfo>();
	
	private TrackUtil mTrackUtil;
	private MapCallUtil mMapCallUtil;
	
	private PointMarkerUtil mPointMarkerUtil;
	
	private MarkerTools markerTools;
	private MeasureUtil mMeasureDistanceUtil;
	
	private List<Marker> mUserLocMarkerList = new ArrayList<Marker>();
	
	private FragmentActivity mActivity;

	private boolean isFirst; 
	private boolean myLocValid = false;
	
	private List<UserInfo> userList = new ArrayList<UserInfo>();
	private List<Polyline> mRemoveLineList = new ArrayList<Polyline>();

	private String mcId;
	private AddrInfo myIdInfo;
	private String mCurrentGroupNameStr = "";
	
	private boolean isShowDistance = false;
	
	private String showMenuId = null;
	private UserInfo mSelectUserInfo;
	private Marker mSelectMarker;
	private boolean isShowCallLayout = false;
	
	private boolean isUserOnline = true;
	
	private Handler myHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UpdateThread.UPDATE_USER_LIST:
				//mMeasureAdapter.notifyDataSetChanged();
				break;
			case UpdateThread.UPDATE_LOCATION:
				myLocationPoint = defaultPoint;
				for(int i = 0; i < mUserLocationList.size(); i++){	
					MapPointInfo pointInfo = mUserLocationList.get(i);
					if(pointInfo != null){
						LocationData locData = pointInfo.getLocationData();
						if(locData.getLattitude() != 0 && locData.getLongitude() !=0){
							GeoPoint p = getGCJGeoPoint(locData.getLattitude(), locData.getLongitude());
							drawUserLocation(pointInfo);
						}
					}
				}
				Log.d(TAG, "myLocationPoint = "+myLocationPoint);
				if(myLocationPoint != defaultPoint){
					double lat_l = myLocationPoint.getLatitude();
					double lng_l = myLocationPoint.getLongitude();
					
					if(lat_l == 0 || lng_l == 0){
						return;
					}
					
					for(Marker marker : mUserLocMarkerList){
						Log.d(TAG, "mUserLocMarkerList = "+mUserLocMarkerList.size());
						if(!marker.getId().equals(mcId)){
							double lat_m = marker.getPosition().getLatitude();
							double lng_m = marker.getPosition().getLongitude();
							float[] results = new float[1];
							Location.distanceBetween(lat_m, lng_m, lat_l, lng_l, results);
							MarkerRoundMenu distanceInfoWindow = (MarkerRoundMenu) marker.getRelatedObject();
							TextView distanceTv = (TextView) ((ViewGroup)distanceInfoWindow.getView()).getChildAt(0);
							distanceTv.setText(String.format("%.1f", results[0])+"m");
							distanceTv.setVisibility(isShowDistance ? View.VISIBLE : View.GONE);
							Log.d(TAG, "draw distance = "+results[0]);
						}
					}
				}else{
					cleanDistanceView();
				}
				break;

			default:
				break;
			}
		};
	};
	
	private ImageButton btnTrackBack;
	private ImageButton btnMeasureDistance;
	
	private double mMinScale;
	private double mMaxScale;
	
	public enum MapViewMode {
		NORMAL, VIDEOCALL, ARMYMARKER, TRACK, DISTANCE
	}
	private MapViewMode mViewMode;

	//private MarkerRoundMenu distanceInfoWindow;
	
	public MapFragment() {
		// TODO Auto-generated constructor stub
	}

	public MapFragment(AddrInfo mcIdInfo) {
		// TODO Auto-generated constructor stub
		myIdInfo = mcIdInfo;
		if(myIdInfo !=null){
			mcId = myIdInfo.getAddrId();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		markerTools = new MarkerTools(mActivity);
//		callFunction = new CallFunction(getActivity());
		CallView = LayoutInflater.from(getContext()).inflate(R.layout.marker_call_layout_, null);
		mMapCallVideoButton = (ImageButton) CallView.findViewById(R.id.video_call_img_btn);
		mMapCallVoiceButton = (ImageButton) CallView.findViewById(R.id.voice_call_img_btn);
		
		initMapConfig();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		View view = inflater.inflate(R.layout.map_layout, container, false);

		mMapView = (MapView) view.findViewById(R.id.myOSMmapview);
		mController = mMapView.getController();
		
		initMapOverlays(mMapView);
		
		mMapView.setBuiltInZoomControls(false);
		mMapView.setMultiTouchControls(true);

		mCurrentGroupTv = (TextView)view.findViewById(R.id.current_group_info);
		mCurrentGroupNameStr = getResources().getString(R.string.empty_number);
		mCurrentGroupTv.setText(mCurrentGroupNameStr);
		
		mCompassView = (CompassView)view.findViewById(R.id.compass_layout);
	    mCompassView.setOnClickListener(this);
	  	    
	    //init rightbutton
	    //back to center
	    mBtnCenterMap = (ImageButton) view.findViewById(R.id.ic_center_map);
	    mBtnCenterMap.setOnClickListener(this);
	    
		//show contact list for draw track line
	    btnTrackBack = (ImageButton) view.findViewById(R.id.ic_track_back);
		btnTrackBack.setOnClickListener(this);
		mContactLv = (ListView) view.findViewById(R.id.lv_track_contact);
		
		//show contact list for draw distance
		btnMeasureDistance = (ImageButton) view.findViewById(R.id.ic_measure);
		btnMeasureDistance.setOnClickListener(this);
	    
	    mZoomButtons = (LinearLayout) view.findViewById(R.id.linear_zoom);
		mZoomIn = (ImageView) view.findViewById(R.id.btn_zoomin);
		mZoomIn.setOnClickListener(this);

		mZoomOut = (ImageView) view.findViewById(R.id.btn_zoomout);
		mZoomOut.setOnClickListener(this);
		
		mMapCallLayout = (RelativeLayout) view.findViewById(R.id.map_call_layout);
		
		mMapCallLayout.setOnClickListener(this);
		
		if(mMapCallVideoButton != null){
			mMapCallVideoButton.setOnClickListener(this);
		}
		
		if(mMapCallVoiceButton != null){
			mMapCallVoiceButton.setOnClickListener(this);
		}
		
		initMarker();
		initTrack();
		initMapCall();
		initPointMarkerUtil();
		initMeasureDistance();
		
		return view;
	}
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mActivity = (FragmentActivity)activity;
	}
	
	
	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

	}
	
	private void initMapConfig(){
		mMinScale = ZOOM_LEVEL_MIN;
		mMaxScale = ZOOM_LEVEL_MAX;
		isFirst = true;
	}
		
	private void initMarker(){
		markerTools.initMap(mMapView);
		markerTools.initPopupWindow();
	}
	
	private void initTrack(){
		mTrackUtil = new TrackUtil(mActivity);
		mTrackUtil.setMapView(mMapView);
		mTrackUtil.initTrackLv(mContactLv);
	}
	
	private void initMapCall(){
		mMapCallUtil = new MapCallUtil(mActivity);
		//mMapCallUtil.setMapView(mMapView);
		//mMapCallUtil.initVideoCallLv(mVideoLv);
	}
	
	private void initPointMarkerUtil(){
		mPointMarkerUtil = new PointMarkerUtil(getActivity(), mMapView);
	}
	
	private void initMeasureDistance(){
		mMeasureDistanceUtil = new MeasureUtil(mActivity);
		mMeasureDistanceUtil.setMapView(mMapView);
		//mMeasureDistanceUtil.initMeasureLv(mMeasureLv);
		
		initMeasureListView();
	}
	
	private void initMeasureListView(){
	}

	public void initMapOverlays(MapView mapView) {
		if (mapView.getOverlays().size() <= 0) {
			mapViewOtherData(mapView, NORMAL_MAP);
			mapView.setDrawingCacheEnabled(true);
			mapView.setMinZoomLevel(mMinScale);
			mapView.setMaxZoomLevel(mMaxScale);
			mController.setZoom(((int)(mMinScale+mMaxScale)/2));
			mapView.setUseDataConnection(true);
			mapView.setMultiTouchControls(true);
			mapView.getOverlayManager().getTilesOverlay().setEnabled(true);
			sCentralParkBoundingBox = new BoundingBox(85.0, 180.0, -85.0, -180.0);
			mapView.setScrollableAreaLimitDouble(sCentralParkBoundingBox);
			
			DisplayMetrics dm = getResources().getDisplayMetrics();
			float statusHeight = getResources().getDimension(getResources().getIdentifier("status_bar_height", "dimen", "android"));
			ScaleBar scaleBarOverlay = new ScaleBar(mapView);
			double mapHeight = dm.heightPixels - statusHeight - (getResources().getDimension(R.dimen.actionbar_height)+getResources().getDimension(R.dimen.bottombar_height));
			int y = (int) (mapHeight*0.95);
			int x = (int) (getResources().getDimension(R.dimen.location_margin));
			Log.d("lq", "statusHeight = "+statusHeight+" mapHeight = "+mapHeight + " y = "+y);
			scaleBarOverlay.setScaleBarOffset(x, y);
			scaleBarOverlay.setMaxLength((float)0.712);	
			scaleBarOverlay.setTextSize(10);
			mMapView.getOverlays().add(scaleBarOverlay);
			
			Point mPoint = PositionUtils.wgs2gcj(118.8157080638228, 32.038093030373815);
			myLocationPoint = new GeoPoint(mPoint.getLat(), mPoint.getLng());//qinheng D3
			defaultPoint = myLocationPoint;
			mController.setCenter(myLocationPoint);
		}
	}
	
	public void mapViewOtherData(MapView mapView, int mapType) {
		
		if(mapView == null){
			return;
		}
		
		String strFilepath = null;
		String fileName = null;
		if (mapType == NORMAL_MAP) {
			strFilepath = Environment.getExternalStorageDirectory().getPath() + "/normal.mbtiles";
			// strFilepath = "file:///android_asset/chinagooglenormal.mbtiles";
			fileName = "normal.mbtiles";
		} else if (mapType == SATALITE_MAP) {
			strFilepath = Environment.getExternalStorageDirectory().getPath() + "/sat.mbtiles";
			// strFilepath = "file:///android_asset/chinagooglesat.mbtiles";
			fileName = "sat.mbtiles";
		} else {
			strFilepath = Environment.getExternalStorageDirectory().getPath() + "/3d.mbtiles";
			// strFilepath = "file:///android_asset/chinagoogle3d.mbtiles";
			fileName = "3d.mbtiles";
		}
		File exitFile = new File(strFilepath);
		Log.d(TAG, "exitFile = "+exitFile.exists());
		if (!exitFile.exists()) {
			mapView.setTileSource(TileSourceFactory.MAPNIK);
		} else {
			fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
			if (fileName.length() == 0)
				return;
			Log.d(TAG, "fileName = "+fileName);
			if (ArchiveFileFactory.isFileExtensionRegistered(fileName)) {
				try {
					OfflineTileProvider tileProvider = new OfflineTileProvider(
							(IRegisterReceiver) new SimpleRegisterReceiver(getActivity()), new File[] { exitFile });
					mapView.setTileProvider(tileProvider);
					String source = "";
					IArchiveFile[] archives = tileProvider.getArchives();
					Log.d(TAG, "archives.length = "+archives.length);
					if (archives.length > 0) {
						Set<String> tileSources = archives[0].getTileSources();
						Log.d(TAG, "tileSources = "+tileSources);
						if (!tileSources.isEmpty()) {
							source = tileSources.iterator().next();
							mapView.setTileSource(FileBasedTileSource.getSource(source));
						} else {
							mapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
						}
					} else
						mapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
					mapView.invalidate();
					return;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else {
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ic_track_back:
			mTrackUtil.showListView(!v.isSelected());
			v.setSelected(!v.isSelected());
			break;
		
		case R.id.btn_zoomin:
			int zi_level = mMapView.getZoomLevel();
			mController.setZoom(++zi_level);
			break;
			
		case R.id.btn_zoomout:
			int zo_level = mMapView.getZoomLevel();
			mController.setZoom(--zo_level);
			break;
			
		case R.id.ic_center_map:
			//mController.animateTo(myLocationPoint);
			if(myLocationPoint == null){
				return;
			}
			mController.setCenter(myLocationPoint);
			mController.zoomTo(getAutoZoom(mUserLocationList));
			break;
			
		case R.id.compass_layout:
			//do nothing
			break;
			
		case R.id.ic_measure:
			Log.d(TAG, "click measure");
			if(v.isSelected())
			{
				btnMeasureDistance.setSelected(!v.isSelected());
				isShowDistance = !isShowDistance;
				cleanDistanceView();
			}
			else
			{
				if(!isMyLocationValid()){
					CommDlg.show(getActivity(), getResources().getString(R.string.cannot_get_my_loc));
				}else{
					btnMeasureDistance.setSelected(!v.isSelected());
					isShowDistance = !isShowDistance;
					showDistanceView();
				}
			}
			
			break;
			
		case R.id.map_call_layout:
			mMapCallLayout.removeAllViews();
			mMapCallLayout.setVisibility(View.GONE);
			isShowCallLayout = false;
			break;
			
		case R.id.video_call_img_btn:
//			CallFunction.makePrivateCall(getActivity(),mSelectUserInfo, CallAttr.CallType_Webrtc_Single,true);
//			mMapCallLayout.removeAllViews();
//			mMapCallLayout.setVisibility(View.GONE);
//			isShowCallLayout = false;
//			break;
			boolean isUserVideo = true;
			
		case R.id.voice_call_img_btn:
//			CallFunction.makePrivateCall(getActivity(),mSelectUserInfo, CallAttr.CallType_Webrtc_Single,false);
			isUserVideo = false;
			SysApplication app = ((SysApplication) getActivity().getApplicationContext());
			Product product = app.getProduct();
			product.getPCallEventAdapter().makePrivateCall(mSelectUserInfo, CallAttr.CallType_Private,isUserVideo,false,"");
			
			mMapCallLayout.removeAllViews();
			mMapCallLayout.setVisibility(View.GONE);
			isShowCallLayout = false;
			break;
			
		default:
			break;
		}
	}
	
	private void drawUserLocation(MapPointInfo mapPointInfo){
		if(mapPointInfo == null){
			return;
		}
		LocationData loc = mapPointInfo.getLocationData();
		final UserInfo userInfo = mapPointInfo.getSender();
		if(loc != null){
			if(!loc.isValid()){
				return;
			}
			double lat = loc.getLattitude();
			double lng = loc.getLongitude();
			GeoPoint newPoint = getGCJGeoPoint(lat, lng);
			if(mMapView == null){
				return;
			}
			Marker userMarker = new Marker(mMapView);
			userMarker.setPosition(newPoint);
			Drawable drawable;
			TextView distanceTv;
			boolean isMyLocation = false;
			
			if(mapPointInfo.isSameOne(myIdInfo)){
				myLocationPoint = newPoint;
				isMyLocation = true;
			}
						
			userMarker.setIcon(changeView2Drawable(userInfo.getName(), mapPointInfo.isSameOne(myIdInfo)));
			userMarker.setDraggable(false);
			userMarker.setInfoWindow(null);
			
			if(userInfo != null){
				userMarker.setTitle(userInfo.getName()+":");
				userMarker.setId(userInfo.getAddrId());
				
				userMarker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
					
					@Override
					public boolean onMarkerClick(Marker marker, MapView mapView) {
						// TODO Auto-generated method stub
						
						/*CommDlg.show(getActivity(), "click number = "+marker.getId());
						if(marker.getId().equals(myMcpttId)){
							return false;
						}
						isShowCallLayout = !isShowCallLayout;
						showMenuId = marker.getId();
						Log.d(TAG, "onMarkerClick showMenuId = "+showMenuId);
						
						mSelectUserInfo = userInfo;
						
						mSelectMarker = marker;
						
						showCallLayout(mSelectMarker.getPosition(), isShowCallLayout);*/
						
						return false;
					}
				});
				
				InfoWindow markinfowindows = new InfoWindow(R.layout.marker_info_window_for_user, mMapView) {
					@Override
					public void onOpen(Object arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onClose() {
						// TODO Auto-generated method stub
					}
				};
				TextView title = (TextView) markinfowindows.getView().findViewById(R.id.marker_title_tv);
				title.setText(userInfo.getName());
				userMarker.setInfoWindow(markinfowindows);
				
				if(isMyLocation){
					markinfowindows.open(null, newPoint, 0, -18);
				}else{
					markinfowindows.open(null, newPoint, 0, -15);
				}
				
				View view = LayoutInflater.from(getContext()).inflate(R.layout.distance_layout, null);
				TextView distanceTextView = (TextView) view.findViewById(R.id.marker_distance_tv);
				MarkerRoundMenu distanceInfoWindow = new MarkerRoundMenu(view, mMapView);
				if(isShowDistance && !isMyLocation){
					distanceInfoWindow.open(this, userMarker, userMarker.getPosition(), 0, 10);
				}else{
					distanceInfoWindow.close();
				}
				userMarker.setRelatedObject(distanceInfoWindow);
			}
			
			if(mMapView != null){
				if(!mMapView.getOverlayManager().contains(userMarker)){
					mMapView.getOverlayManager().add(userMarker);
					mUserLocMarkerList.add(userMarker);
					if(mSelectMarker != null && mSelectMarker.getId().equals(userMarker.getId())){
						mSelectMarker = userMarker;
					}
				}
				
				if(isFirst && isMyLocation){
					mController.setCenter(myLocationPoint);
					isFirst = false;
				}
				mMapView.invalidate();
				
				if(mSelectMarker != null){
					showCallLayout(mSelectMarker.getPosition(), isShowCallLayout);
				}
			}
		}
	}
	
	private Drawable changeView2Drawable(String num, boolean isMyself){
		/*View view = LayoutInflater.from(getContext()).inflate(R.layout.custom_marker_layout, null);
		TextView textView = (TextView) view.findViewById(R.id.marker_user_name);
		textView.setText(num);
		
		ImageView imageView = (ImageView) view.findViewById(R.id.marker_user_icon);
		imageView.setImageDrawable(isMyself ? 
									getResources().getDrawable(R.drawable.map_my_location_marker_icon) : 
									getResources().getDrawable(R.drawable.map_other_location_marker));
	
		view.setDrawingCacheEnabled(true);
		view.measure(
				View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 
				View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		view.layout(0, 0, 
				view.getMeasuredWidth(), 
				view.getMeasuredHeight());
		view.buildDrawingCache();
		Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
		Drawable drawable = new BitmapDrawable(bitmap);*/
		
		Drawable drawable = isMyself ? 
				getResources().getDrawable(R.drawable.map_my_location_marker_icon) : 
				getResources().getDrawable(R.drawable.map_other_location_marker);
		
		return drawable;
	}
	
	private void clearAllUserLocationMarker(){
		
		for(Marker marker : mUserLocMarkerList){
			if(mMapView != null){
				if(marker.getInfoWindow() != null){
					marker.closeInfoWindow();
				}
				
				if(marker.getRelatedObject() != null){
					MarkerRoundMenu menu = (MarkerRoundMenu)marker.getRelatedObject();
					menu.close();
				}
				//marker.remove(mMapView);
				
				mMapView.getOverlays().remove(marker);
			}
		}
		
		if(mMapCallLayout != null && mMapCallLayout.getVisibility() == View.VISIBLE){
			mMapCallLayout.removeAllViews();
			if(!isUserOnline){
				mMapCallLayout.setVisibility(View.GONE);
			}
		}
		
		mUserLocationList.clear();
		mUserLocMarkerList.clear();
	}

	private void cleanDistanceView(){
		
		for(Marker marker : mUserLocMarkerList){
			MarkerRoundMenu distanceInfoWindow = (MarkerRoundMenu) marker.getRelatedObject();
			TextView tv = (TextView) ((ViewGroup)distanceInfoWindow.getView()).getChildAt(0);
			tv.setVisibility(View.GONE);
		}
	}
	
	private void showDistanceView(){
				
		new Thread(new UpdateThread(UpdateThread.UPDATE_LOCATION)).start();
		
		/*for(Marker marker : mUserLocMarkerList){
			InfoWindow infoWindow = (InfoWindow) marker.getInfoWindow();
			//TextView tv = (TextView) infoWindow.getView("distance");
			MarkerRoundMenu distanceInfoWindow = (MarkerRoundMenu) marker.getRelatedObject();
			TextView tv = (TextView) ((ViewGroup)distanceInfoWindow.getView()).getChildAt(0);
			if(marker.getId().equals(myMcpttId)){
				tv.setVisibility(View.GONE);
			}else{
				tv.setVisibility(View.VISIBLE);
			}
		}*/
		
	}

	public void onUpdateNewData(String currentGroup, List<UserInfo> list,List<MapPointInfo> mpList) {
		//this.userList = list;
		//this.mUserLocationList = mpList;
		
		if(!mCurrentGroupNameStr.equals(currentGroup)){
			mCurrentGroupNameStr = currentGroup;
			if(this.isAdded())
			{
				mCurrentGroupTv.setText(String.format(getResources().getString(R.string.current_group_info), mCurrentGroupNameStr));
			}
		}
				
		if(mMapCallUtil != null){
			//update map call list
			//mMapCallUtil.updateData(list);
			userList = list;
			//mMapCallUtil.updateData(userList);
		}
		
		if(mTrackUtil != null){
			//update map track list
			mTrackUtil.updateData();
		}
		
		clearAllUserLocationMarker();
		
		if(mpList.size() > 0){
			mUserLocationList = mpList;
			new Thread(new UpdateThread(UpdateThread.UPDATE_LOCATION)).start();
		}
	}
	
	private void addMeasureMarker(GeoPoint p, int drawableId){
		mPointMarkerUtil.addMarkerToMap(p, drawableId, null, PointMarkerUtil.TYPE_MEASUER);
		invalidate();
	}
	
	private void invalidate(){
		if(mMapView != null){
			mMapView.invalidate();
		}
	}
	
	private int getAutoZoom(List<MapPointInfo> list){
		
		double minLat = Double.MAX_VALUE;
		double minLon = Double.MAX_VALUE;
		double maxLat = Double.MIN_VALUE;
		double maxLon = Double.MIN_VALUE;
		for (final MapPointInfo mp : list) {
			if(mp.isValid()){
				final double latitude = mp.getLocationData().getLattitude();
				final double longitude = mp.getLocationData().getLongitude();
				minLat = Math.min(minLat, latitude);
				minLon = Math.min(minLon, longitude);
				maxLat = Math.max(maxLat, latitude);
				maxLon = Math.max(maxLon, longitude);
			}
		}
	
		float[] results = new float[1];
		Location.distanceBetween(maxLat, maxLon, minLat, minLon, results);
		for(int i = 0; i < ZOOM.length; i++){
			if((ZOOM[i] - results[0])>0){
				
				return 18-i+1;
			}
		}
		return 15;
	}
	
	private boolean isMyLocationValid(){
		myLocValid = false;
		Log.d(TAG, "myMcpttId = "+mcId);
		for(Marker locaMarker : mUserLocMarkerList){
			Log.d(TAG, "locaMarker.getId() = "+locaMarker.getId());
			if(locaMarker.getId().equals(mcId)){
				Log.d(TAG, "myLocValid = true");
				myLocValid = true;
			}
		}
		return myLocValid;
	}
	
	private GeoPoint getGCJGeoPoint(double lat, double lng){
		Point mPoint = PositionUtils.wgs2gcj(lng,lat);
		GeoPoint newPoint = new GeoPoint(mPoint.getLat(), mPoint.getLng());
		return newPoint;
	}
		
	class UpdateThread implements Runnable{
		
		public static final int UPDATE_USER_LIST = 1;
		public static final int UPDATE_LOCATION = 2;
		public static final int REMOVE_LINE = 4;
		
		private int what = -1;
		
		public UpdateThread(int what) {
			// TODO Auto-generated constructor stub
			this.what = what;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message message = myHandler.obtainMessage();
			message.what = what;
			
			myHandler.sendMessage(message);
		}
	}
	
	public void setMyLoginInfo(AddrInfo myInfo){
		this.myIdInfo = myInfo;
		if(myIdInfo !=null){
			mcId = myIdInfo.getAddrId();
		}
		
		mapViewOtherData(mMapView, NORMAL_MAP);
	}
	
	private void showCallLayout(GeoPoint point, boolean show){
		
		if(mMapCallLayout != null && show){
			mMapCallLayout.setVisibility(View.VISIBLE);
			Projection projection = mMapView.getProjection();
			int x = (int) projection.getLongPixelXFromLongitude(point.getLongitude());
			int y =  (int) projection.getLongPixelYFromLatitude(point.getLatitude());
			
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
			layoutParams.setMargins(x-60, y-120, 0, 0);

			CallView.layout(x, y, 
					CallView.getMeasuredWidth(), 
					CallView.getMeasuredHeight());
			mMapCallLayout.removeAllViews();
			mMapCallLayout.addView(CallView,layoutParams);
		}
	}
	
	public void setStatusOnLine(boolean isOnline){
		isUserOnline = isOnline;
		
		if(isUserOnline == false){
			clearAllUserLocationMarker();
		}
	}
}
